package Dao.Impl;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static Logger logger = Logger.getLogger(BaseDao.class);
    //驱动
    private static String DRIVER;
    //数据库连接地址
    private static String URL;
    //用户名
    private static String USER;
    //密码
    private static String PWD;

    static {
        String configFile = "database.properties";
        try (
                InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile)) {
            Properties properties = new Properties();
            //读取配置文件信息
            properties.load(is);
            DRIVER = properties.getProperty("driver");
            URL = properties.getProperty("url");
            USER = properties.getProperty("user");
            PWD = properties.getProperty("password");
        } catch (IOException e) {
            logger.error("加载数据库配置文件失败！", e);
        }
        //加载驱动
        try {
            Class.forName(DRIVER);
            logger.debug("驱动加载成功！");
        } catch (ClassNotFoundException e) {
            logger.error("加载驱动失败！", e);
        }
    }

    protected Connection getConnection() throws SQLException {
        Connection conn = null;
        conn = DriverManager.getConnection(URL, USER, PWD);
        return conn;
    }

    protected void releaseResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
//注释：这是一个基础的Dao类，用于获取数据库连接和释放资源。其中包含了读取数据库配置文件和加载驱动的方法。